package com.soft.javase.day12;

/**
 * @author yzg
 * @desc TODO
 * @date 2025/5/19
 */
public class TicketSale {
    private int ticketCount;

    public TicketSale(int count) {
        this.ticketCount = count;
    }

    public int sale() {
        synchronized (this) {
            if (ticketCount > 0) {
                System.out.println(Thread.currentThread().getName()
                        + " 购买到票，票号: " + ticketCount--
                        + "，剩余票数: " + ticketCount);
                return ticketCount +1;
            } else {
                System.out.println(Thread.currentThread().getName()
                        + " 购票失败，票已售完");
                return 0;
            }
        }
    }

    public static void main(String[] args) {
        TicketSale ticketSale = new TicketSale(20);
        for (int i = 1; i < 6; i++) {
            new Thread(()->{
                while(true){
                    int ticket = ticketSale.sale();
                    if(ticket == 0){
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            },"售票口"+i).start();
        }
    }
}

